package com.giscafer.user;

import com.giscafer.common.model.User;
import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.jfinal.json.FastJson;
import com.jfinal.kit.HttpKit;
import com.jfinal.kit.Ret;
import top.jwtTokenPlugin.annotation.Auth;
import top.jwtTokenPlugin.interceptor.JwtTokenInterceptor;
import top.jwtTokenPlugin.kit.JwtKit;

import java.util.Map;


/**
 * 用户控制器，注册登录等
 * UserController
 */
public class UserController extends Controller {

    static UserService service = new UserService();

//    public void index() {
//        setAttr("userPage", service.paginate(getParaToInt(0, 1), 10));
//        render("user.html");
//    }

    /**
     * 新增用户
     */
    public void add() {
        getModel(User.class).save();
        redirect("/user");
    }

    /**
     * 用户信息查询
     */
    public void query() {
        User user = null;
        String id = getPara("userId");
//        int userId = getParaToInt("userId");
        String userName = getPara("userName");
        if (id != null && !"".equals(id)) {
            user = service.findById(Integer.parseInt(id));
        } else if (userName != null && !"".equals(userName)) {
            user = service.findByUserName(userName);
        }
        renderJson(user);
    }

    /**
     * 用户信息更新
     */
    public void update() {
        getModel(User.class).update();
        redirect("/user");
    }

    /**
     * 用户登录
     */
    public void login() {
        // 获取json对象转为User Model
        String jsonString = HttpKit.readData(getRequest());
        User user = FastJson.getJson().parse(jsonString, User.class);
        System.out.println(jsonString);
        // 获取token
        try{
            String token =token = JwtKit.getToken(user.getUsername(), user.getPassword());
            System.out.println(token);
            renderJson(Ret.by("token", token));
        }catch (Exception e){
            renderJson(Ret.fail());
        }

    }

    // 登录认证
    @Before(JwtTokenInterceptor.class)
    public void testLogin() {
        renderJson(Ret.ok());
    }

    @Auth(hasRoles = {"管理员"})
    public void testHasRole() {
        renderJson(Ret.ok());
    }

    @Auth(hasForces = {"登录后台"})
    public void testHasForce() {
        renderJson(Ret.ok());
    }

    @Auth(withRoles = {"管理员", "普通用户"})
    public void testWithRoles() {
        renderJson(Ret.ok());
    }

    @Auth(withForces = {"登录后台", "管理用户"})
    public void testWithForces() {
        renderJson(Ret.ok());
    }
}

